import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import axios from '../../utils/index'
import {
  Form,
  Input,
  Button,
  Toast
} from 'antd-mobile'
import {
  Down,
  Contact
} from '@react-vant/icons'

import {
  LockOutline,
  EyeInvisibleOutline,
  EyeOutline,
  PhoneFill,
} from 'antd-mobile-icons'
import './Login.css'

export default function Login() {

  const navigate = useNavigate()

  const [show, setShow] = useState('A')
  const [visible, setVisible] = useState(false)
  const [phone, setPhone] = useState("")
  const [yzmnum, setYzmnum] = useState("")
  const [reqyzm, setReqyzm] = useState("")

  // 密码和手机号登录
  // const [form] = Form.useForm()
  const handleLogin = async (values) => {
    // const values = form.getFieldsValue()
    console.log(values);
    if (values.password) {
      let  data  = await axios.post("/login", values)
      if (data.code === 200) {
        // console.log(data.user);
        localStorage.setItem("accessToken", data.accessToken)
        localStorage.setItem("refreshToken", data.refreshToken)
        localStorage.setItem("user", JSON.stringify(data.user))
        localStorage.setItem("userid", JSON.stringify(data.user._id))
        navigate("/all/home")
        Toast.show({
          content: '登录成功',
        })
      } else {
        Toast.show({
          content: '登录失败',
        })
      }
    } else if (values.phonenum) {
      let  data  = await axios.post("/login", values)
      if (yzmnum === reqyzm) {
        // console.log(data.user);
        localStorage.setItem("accessToken", data.accessToken)
        localStorage.setItem("refreshToken", data.refreshToken)
        localStorage.setItem("user", JSON.stringify(data.user))
        localStorage.setItem("userid", JSON.stringify(data.user._id))
        navigate("/all/home")
        Toast.show({
          content: '登录成功',
        })
      } else {
        Toast.show({
          content: '手机号或验证码输入不正确',
        })
      }
    }
  }

  // 注册
  const handleRegister = async (values) => {
    values.wallet = 0;
    values.img = "/car.jpeg"
    let  data  = await axios.post("/register", values)
    if (data.code === 200) {
      const timer = setInterval(() => {
        setShow("A")
        clearInterval(timer)
      }, 1000)
      Toast.show({
        content: '注册成功',
      })
    } else {
      Toast.show({
        content: '该用户已注册',
      })
    }
  }

  // 发送验证码
  const handleSendYzm = async () => {
    let obj = {
      phone: phone,
      yzm: yzmnum
    }
    let  data  = await axios.post("/send", obj)
    // console.log(data);
    if (data.code === 200) {
      setReqyzm(data.randomNumber)
      Toast.show({
        content: data.msg
      })
    } else {
      Toast.show({
        content: "验证码发送失败"
      })
    }
  }

  return (
    <div className='login'>
      <div className='login-box'>


        <Down className='login-icon' />
        {
          show == 'A' ? <div className='login-title'>登录您的账号</div>
            : <></>
        }
        {
          show == "B" ? <div className='login-title'>验证码登录</div>
            : <></>
        }
        {
          show == "C" ? <div className='login-title'>请注册账号</div>
            : <></>
        }

        {/* form={form} */}
        {/* 密码登录 */}
        {
          show === 'A' ? <Form layout='horizontal' className='login-form' onFinish={handleLogin}
            footer={
              <Button type='submit' className='login-btn'>
                登录
              </Button>
            }
          >
            <Form.Item name='username' className='login-form-item'
              rules={[{ required: true, message: '用户名不能为空!' }]}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Contact className='login-form-icon' />
                <Input placeholder='请输入用户名' inputMode='text' clearable className='.login-form-input' />
              </div>
            </Form.Item>
            <Form.Item name='password' inputMode='text' className='login-form-item'
              rules={[
                { required: true, message: "请输入密码" },
                { type: 'string', min: 6, max: 11, message: "密码要在6-11个字符之间" },
                // { type: 'email', warningOnly: true },
              ]}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <LockOutline className='login-form-icon' />
                <Input placeholder='请输入密码' clearable type={visible ? 'text' : 'password'} className='.login-form-input' />
                <div className="login-input-eye">
                  {!visible ? (<EyeInvisibleOutline onClick={() => setVisible(true)} />) : (<EyeOutline onClick={() => setVisible(false)} />)}
                </div>
              </div>
            </Form.Item>
          </Form>
            : <></>
        }
        {/* 手机号验证码登录 */}
        {
          show === 'B' ? <Form layout='horizontal' className='login-form' onFinish={handleLogin}
            footer={
              // <div>
              <Button type='submit' className='login-btn'>
                登录
              </Button>
              // </div>
            }
          >
            <Form.Item name='username' className='login-form-item'
              rules={[{ required: true, message: '用户名不能为空!' }]}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Contact className='login-form-icon' />
                <Input placeholder='请输入用户名' clearable className='.login-form-input' />
              </div>
            </Form.Item>
            <Form.Item name='phonenum' className='login-form-item'
              rules={[
                { required: true, message: "请输入手机号" },
                { type: 'string', max: 11, message: "请输入正确的手机号" },
              ]}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <PhoneFill className='login-form-icon' />
                <Input placeholder='请输入手机号' clearable type='text' className='.login-form-input'
                  value={phone} onChange={(e) => { setPhone(e) }}
                />
              </div>
            </Form.Item>
            <div style={{ display: 'flex', justifyContent: "space-around" }}>
              <Form.Item name='yzmnum' className='login-form-item-yzm'
                rules={[{ required: true, message: '验证码不能为空!' }]}
              >
                <Input placeholder='请输入验证码' clearable type='text' className='.login-form-input'
                  value={yzmnum} onChange={(e) => { setYzmnum(e) }}
                />
              </Form.Item>
              <Button className='login-btnyzm' onClick={handleSendYzm} >获取验证码</Button>
            </div>

          </Form>
            : <></>
        }
        {/* 注册 */}
        {
          show === 'C' ? <Form layout='horizontal' className='login-form' onFinish={handleRegister}
            footer={
              <Button type='submit' className='login-btn'>
                注册
              </Button>
            }
          >
            <Form.Item name='username' className='login-form-item'
              rules={[{ required: true, message: '用户名不能为空!' }]}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Contact className='login-form-icon' />
                <Input placeholder='请输入用户名' clearable className='.login-form-input' />
              </div>
            </Form.Item>
            <Form.Item name='password' className='login-form-item'
              rules={[
                { required: true, message: "请输入密码" },
                { type: 'string', min: 6, max: 11, message: "密码要在6-11个字符之间" },
                // { type: 'email', warningOnly: true },
              ]}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <LockOutline className='login-form-icon' />
                <Input placeholder='请输入密码' clearable type={visible ? 'text' : 'password'} className='.login-form-input' />
                <div className="login-input-eye">
                  {!visible ? (<EyeInvisibleOutline onClick={() => setVisible(true)} />) : (<EyeOutline onClick={() => setVisible(false)} />)}
                </div>
              </div>
            </Form.Item>
            <Form.Item name='phonenum' className='login-form-item'
              rules={[{ required: true, message: '手机号不能为空!' }]}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <PhoneFill className='login-form-icon' />
                <Input placeholder='请输入手机号' clearable className='.login-form-input' />
              </div>
            </Form.Item>
          </Form>
            : <></>
        }

        <div className='login-middle'>
          {
            show === 'A' ? <span className='login-middle-text' onClick={() => setShow('B')}>忘记密码</span>
              : <></>
          }
          {
            show === 'B' ? <span className='login-middle-text' onClick={() => setShow('A')}>密码登录</span>
              : <></>
          }
        </div>

        {
          show !== "C" ? <div className='login-bottom'>
            {/* <Button className='login-btn' onClick={handleLogin}>登录</Button> */}
            <p className='login-bottom-text'>
              <span>没有账户？</span>
              <span style={{ color: "#f9b109", fontWeight: 'bold' }} onClick={() => { setShow("C") }} >注册</span>
            </p>
          </div>
            : <div className='login-bottom'>
              <p className='login-bottom-text'>
                <span onClick={() => { setShow("A") }}>返回登录</span>
              </p>
            </div>
        }

      </div>
    </div>
  )
}
